<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="设备id" prop="clientId">
        <el-input
          v-model="queryParams.clientId"
          placeholder="请输入设备id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否在线" prop="online">
        <el-select v-model="queryParams.online" placeholder="请选择是否在线" clearable>
          <el-option
            v-for="dict in dict.type.bis_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dingwei:DingweiClient:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dingwei:DingweiClient:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dingwei:DingweiClient:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dingwei:DingweiClient:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-position"
          size="mini"
          @click="handleAllLocation"
        >查看所有设备当前位置</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ClientList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备id" align="center" prop="clientId" />
      <el-table-column label="设备名称" align="center" prop="name" />
      <el-table-column label="是否在线" align="center" prop="online">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bis_yes_no" :value="scope.row.online"/>
        </template>
      </el-table-column>      <el-table-column label="最近上线时间" align="center" prop="lastOnlineTime" width="180"/>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.type=='2' && scope.row.online=='1'"
            icon="el-icon-edit"
            @click="handleOnlineVideo(scope.row)"
          >查看实时视频</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleNowLocation(scope.row)"
          >查看实时位置</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRecord(scope.row)"
          >查看历史轨迹</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dingwei:DingweiClient:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dingwei:DingweiClient:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="设备名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入设备名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备id" prop="clientId">
              <el-input v-model="form.clientId" placeholder="请输入设备id" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最近上线时间" prop="lastOnlineTime">
              <el-date-picker clearable
                              disabled
                              v-model="form.lastOnlineTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择最近上线时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="历史轨迹" :visible.sync="record.open" width="1300px" append-to-body>
      <el-row :gutter="24" style=" display: flex;  align-items: center;">
        <el-col :span="3">
          查询轨迹向前推移
        </el-col>
        <el-col :span="6">
        <el-row style=" display: flex;  align-items: center;">
          <el-col :span="16">
            <el-input v-model="recordParam.value" type="number" placeholder="请输入内容"/>
          </el-col>
          <el-col :span="8">
            <el-select v-model="recordParam.unit">
              <el-option label="分钟" value="minute"></el-option>
              <el-option label="小时" value="hour"></el-option>
              <el-option label="天" value="day"></el-option>
              <el-option label="月" value="month"></el-option>
            </el-select>
          </el-col>
        </el-row>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="recordQuery">搜索</el-button>
        </el-col>
      </el-row>
      <LocationRecord :trackPoints="record.trackPoints" :key="record.open"></LocationRecord>
    </el-dialog>
    <el-dialog title="实时位置" :visible.sync="nowLocation.open" width="1300px" append-to-body>
      <nowLocation :lat="nowLocation.lat" :lng="nowLocation.lng" :time="nowLocation.time" :key="nowLocation.open"></nowLocation>
    </el-dialog>
    <el-dialog title="所有设备实时位置" :visible.sync="allLocation.open" width="1300px" append-to-body>
      <div style="height: 900px">
      <all-location ref="allLocation"></all-location>
      </div>
    </el-dialog>
    <el-dialog title="实时视频" :visible.sync="onlineVideo.open" width="1500px" append-to-body>
        <onlineVideo :row="onlineVideo.row":isPopupVisible="onlineVideo.open" :videoUrls="onlineVideo.videoUrls" ref="onlineVideo" :key="onlineVideo.open"></onlineVideo>
    </el-dialog>
  </div>
</template>

<script>
import coordtransform from 'coordtransform';
import { listClient, getClient, delClient, addClient, updateClient,getClientLocationRecordByClientId,getNowLocationByClientId,getAllClientNowLocation } from "@/api/dingwei/Client";
import LocationRecord from "@/views/dingwei/Client/record/index.vue";
import nowLocation from "@/views/dingwei/Client/nowLocation/index.vue";
import allLocation from "@/views/dingwei/Client/allLocation/index.vue";
import onlineVideo from "@/views/dingwei/Client/onlineVideo/index.vue";
export default {
  name: "Client",
  dicts: ['bis_yes_no'],
  components: {LocationRecord,nowLocation,allLocation,onlineVideo},
  data() {
    return {
      onlineVideo:{
        open: false,
        row:{},
        videoUrls: [],
        ip:'192.168.20.76',
      },
      allLocation:{
        open: false,
        trackPoints: [
          {
            clientId: undefined,
            lat: undefined,
            lng: undefined,
            time: undefined,
          }
        ],
      },
      nowLocation:{
        open: false,
        lat: undefined,
        lng: undefined,
        time: undefined,
      },
      recordParam: {
        clientId: undefined,
        value: 1,
        unit: 'day',
      },
      record:{
        open: false,
        trackPoints: [],
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备信息表格数据
      ClientList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        clientId: null,
        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询设备信息列表 */
    getList() {
      this.loading = true;
      listClient(this.queryParams).then(response => {
        this.ClientList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        clientId: null,
        name: null,
        online: null,
        lastOnlineTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备信息";
    },
    handleOnlineVideo(row) {
      this.onlineVideo.videoUrls=[]
      for (let i = 1; i <=4; i++) {
        this.onlineVideo.videoUrls.push(' http://'+this.onlineVideo.ip+'/live?app=live&stream=0'+row.clientId+'-'+i+'');
      }
      this.onlineVideo.row = row;
      this.onlineVideo.open=true
    },
    /** 查看实时位置 */
    handleNowLocation(row) {
      getNowLocationByClientId(row.clientId).then(res => {
        let data = res.data
        let trackPoint =  coordtransform.wgs84togcj02(data.lng, data.lat);
        this.nowLocation.open = true;
        this.nowLocation.lng = trackPoint[0];
        this.nowLocation.lat = trackPoint[1];
        this.nowLocation.time=data.timestamp
      })
    },
    recordQuery() {
      getClientLocationRecordByClientId(this.recordParam).then(res => {
        let trackPoints = [];
        for (let i = 0; i < res.data.length; i++) {
          let data = res.data[i]
          let trackPoint = coordtransform.wgs84togcj02(data.lng, data.lat);
          trackPoints.push(trackPoint);
        }
        this.record.trackPoints = trackPoints;
      });
    },
    /** 查看历史轨迹 */
    handleRecord(row) {
      this.recordParam.unit="day"
      this.recordParam.value=1
      this.recordParam.clientId=row.clientId
      getClientLocationRecordByClientId(this.recordParam).then(res => {
        this.record.open=true
        let trackPoints = [];
        for (let i = 0; i < res.data.length; i++) {
          let data=res.data[i]
          let trackPoint =  coordtransform.wgs84togcj02(data.lng, data.lat);
          trackPoints.push(trackPoint);
        }
        this.record.trackPoints = trackPoints;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getClient(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateClient(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addClient(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除数据？').then(function () {
        return delClient(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bis/Client/export', {
        ...this.queryParams
      }, `Client_${new Date().getTime()}.xlsx`)
    },
    handleAllLocation() {
      let trackPoints = []
      this.allLocation.open = true
      getAllClientNowLocation().then(response => {
        response.data.forEach(item => {
          let trackPoint = coordtransform.wgs84togcj02(item.lng, item.lat);
          trackPoints.push({
            clientId: item.clientId,
            lng: trackPoint[0],
            lat: trackPoint[1],
            time: item.timestamp,
          })
        })
        this.$refs['allLocation'].init(trackPoints);
      });
    }
  }
};
</script>
